﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TeamFoundation;
using Microsoft.VisualStudio.TeamFoundation.VersionControl;
using Microsoft.VisualStudio.TeamFoundation.WorkItemTracking;
using System.Data.SqlClient;
using Microsoft.Data.ConnectionUI;
using Microsoft.VisualStudio.Data.Services;

namespace TFSExt.ModifyCheckinDate
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [ProvideOptionPage(typeof(OptionPageGrid), "TFS Productivity Tools", "General", 0, 0, true)]
    [Guid(GuidList.guidModifyCheckinDatePkgString)]
    public sealed class ModifyCheckinDatePackage : Package
    {
        private EnvDTE.DTE dte = null;
        private TfsTeamProjectCollection tfscoll = null;
        private VersionControlServer vcsrv = null;
        private VersionControlExt vcext = null;
        private string AppTitle = null;
        
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public ModifyCheckinDatePackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        private void InitializeExtVariables()
        {
            dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
            //IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));

            var TFSExt = dte.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt") as TeamFoundationServerExt;
            vcext = dte.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt") as VersionControlExt;

            tfscoll = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(TFSExt.ActiveProjectContext.DomainUri));
            tfscoll.Connect(Microsoft.TeamFoundation.Framework.Common.ConnectOptions.None);
            tfscoll.EnsureAuthenticated();

            vcsrv = (VersionControlServer)tfscoll.GetService(typeof(VersionControlServer));

            AppTitle = Resources.ResourceManager.GetString("AppTitle");

            var outputWindow = GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
            var dialogFactory = GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

            DocumentService docsrv2 = (DocumentService)GetService(typeof(DocumentService));

            Utilities.dialogFactory = dialogFactory;
            Utilities.outputWindow = outputWindow;
            Utilities.AppTitle = AppTitle;
        }

        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                var menuCommandID = new CommandID(GuidList.guidModifyCheckinDateCmdSet, (int)PkgCmdIDList.MySCQuModifyTimeID);
                var menuItem = new MenuCommand(MySCQuModifyTimeIDCallback, menuCommandID);
                mcs.AddCommand(menuItem);

                menuCommandID = new CommandID(GuidList.guidModifyCheckinDateCmdSet, (int)PkgCmdIDList.MyHistModifyTimeID);
                menuItem = new MenuCommand(MyHistModifyTimeCallback, menuCommandID);
                mcs.AddCommand(menuItem);

                menuCommandID = new CommandID(GuidList.guidModifyCheckinDateCmdSet, (int)PkgCmdIDList.MySCHistModifyTimeID);
                menuItem = new MenuCommand(MySCHistModifyTimeCallback, menuCommandID);
                mcs.AddCommand(menuItem);
            }
        }
        #endregion

        /// <summary>
        /// Menu callback event handler that updates files date/time attribute in local workspace to their latest check-in date/time.
        /// See <b>Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlHistoryExt</b>
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MySCHistModifyTimeCallback(object sender, EventArgs e)
        {
            InitializeExtVariables();

            //MessageBox.Show("Update Modification Time");
            Workspace wrkspc = vcext.Explorer.Workspace;
            int[] chids = vcext.History.ActiveWindow.SelectedChangesets.Select(x => x.ChangesetId).ToArray();

            foreach (int chid in chids)
            {
                Changeset ch = vcsrv.GetChangeset(chid);

                foreach (var itm in ch.Changes.Select(x => x.Item))
                {
                    if (itm.DeletionId > 0 || itm.ItemType != ItemType.File) continue;

                    string localitm = wrkspc.GetLocalItemForServerItem(itm.ServerItem, true);
                    if (!File.Exists(localitm)) continue;

                    File.SetAttributes(localitm, File.GetAttributes(localitm) & ~FileAttributes.ReadOnly);
                    File.SetLastWriteTime(localitm, itm.CheckinDate);

                    Utilities.OutputCommandString("Set modification date for file: " + localitm + " to " + itm.CheckinDate.ToShortDateString());
                }
            }


            return;
        }

        /// <summary>
        /// Menu callback event handler that updates files date/time attribute in local workspace to their latest check-in date/time.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MySCQuModifyTimeIDCallback(object sender, EventArgs e)
        {
            InitializeExtVariables();

            Workspace wrkspc = vcext.Explorer.Workspace;

            foreach (string serverPath in vcext.Explorer.SelectedItems.Select(x => x.SourceServerPath))
            {
                foreach (Item itm in vcsrv.GetItems(serverPath, RecursionType.Full).Items)
                {
                    if (itm.DeletionId > 0 || itm.ItemType != ItemType.File) continue;

                    string localitm = wrkspc.GetLocalItemForServerItem(itm.ServerItem, true);
                    if (!File.Exists(localitm)) continue;

                    File.SetAttributes(localitm, File.GetAttributes(localitm) & ~FileAttributes.ReadOnly);
                    File.SetLastWriteTime(localitm, itm.CheckinDate);

                    Utilities.OutputCommandString("Set modification date for file: " + localitm + " to " + itm.CheckinDate.ToShortDateString());
                }
            }
        }

        /// <summary>
        /// Menu callback event handler that updates Changesets check-in date/time attribute in TFS database.
        /// See <b>Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlHistoryExt</b>
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MyHistModifyTimeCallback(object sender, EventArgs e)
        {
            InitializeExtVariables();

            //MessageBox.Show("Update Changeset Time");
            int[] chids = vcext.History.ActiveWindow.SelectedChangesets.Select(x => x.ChangesetId).ToArray();
            if (chids == null || chids.Length == 0) return;

            string datevalue = Microsoft.VisualBasic.Interaction.InputBox("Enter new value for Source Path", AppTitle, DateTime.Now.ToString("G"));
            if (string.IsNullOrWhiteSpace(datevalue)) return;

            DateTime dt;

            try
            {
                dt = DateTime.Parse(datevalue);
            }
            catch
            {
                MessageBox.Show("Invalid Date/Time specified.");
                return;
            }

            //connect to TFS database
            //using [DefaultCollection]
            //update table: UPDATE tbl_Changeset SET CreationDate=’?’ WHERE ChangeSetId=‘?’

            var connstr = (string)dte.Properties["TFS Productivity Tools", "General"].Item("TFSConnString").Value;
            if (string.IsNullOrEmpty(connstr))
            {
                Utilities.OutputCommandString("Connection string to TFS database is empty. Set it in Visual Studio Tools -> Options -> TFS Productivity Tools");
            }
            else
            {
                
                var sqlconn = new SqlConnection(connstr);
                try
                {
                    sqlconn.Open();
                    var sqlcmd = sqlconn.CreateCommand();
                    sqlcmd.CommandText = "UPDATE tbl_Changeset SET CreationDate=@date WHERE ChangeSetId in (" + chids.Aggregate("0", (x, y) => x + "," + y) + ")";
                    sqlcmd.Parameters.AddWithValue("@date", dt);
                    int res = sqlcmd.ExecuteNonQuery();
                    Utilities.OutputCommandString("Set Check-in date for Changesets: " + chids.Aggregate("", (x, y) => x + "," + y) + " to " + dt.ToShortDateString() + ", affected records: " + res);
                }
                catch(Exception ex)
                {
                    Utilities.OutputCommandString("Set Check-in date for Changeset: " + chids + " failed. Error: " + ex.ToString());
                }
                finally
                {
                    sqlconn.Close();
                }
            }
            
            return;
        }

        private void ShowSQLConnectionDialog()
        {
            //var dlg = new DataConnectionDialog();
            //DataSource.AddStandardDataSources(dlg);
            //dlg.SelectedDataSource = DataSource.SqlDataSource;
            //if (DataConnectionDialog.Show(dlg) == System.Windows.Forms.DialogResult.OK)
            //    MessageBox.Show(dlg.ConnectionString);

            var dataconnfc = GetService(typeof(IVsDataConnectionDialogFactory)) as IVsDataConnectionDialogFactory;
            var dlg = dataconnfc.CreateConnectionDialog();
            dlg.AddAllSources();
            dlg.SelectedSource = new Guid("{067ea0d9-ba62-43f7-9106-34930c60c528}");
            dlg.SelectedProvider = new Guid("{91510608-8809-4020-8897-fba057e22d54}");
            dlg.SafeConnectionString = (string)dte.Properties["TFS Productivity Tools", "General"].Item("TFSConnString").Value;
            
            if(dlg.ShowDialog())
            {
                dte.Properties["TFS Productivity Tools", "General"].Item("TFSConnString").Value = dlg.SafeConnectionString;
            }

            dlg.Dispose();
        }
    }
}
